# -*- coding: utf-8 -*-
"""
Created on Wed Mar 26 11:14:23 2025

@author: huangyue
"""






from .GetDataInfodb import get_existedinfo

import pymssql
import datetime
import pandas as pd


# 连接infodb的参数
server_zs = "infodb"



# %% 直接从FI_CBSeriesIndicators提取数据

def get_exsiteddata_from_FI_CBSeriesIndicator(cursor, indicators = None, begdate=None, enddate=None):
    # 提取历史上的模型拟合数据
    # enddate当天的数据也会提取
    
    if isinstance(begdate,datetime.datetime):
        begdate = begdate.strftime('%Y-%m-%d')
    if isinstance(enddate,datetime.datetime):
        enddate = enddate.strftime('%Y-%m-%d')
    
    # 日期处理
    if (begdate is None) & (enddate is not None):
        str_daycondition =  '''
                            KeyDate <= '%s' 
                            ''' %(enddate)
    elif (begdate is not None) & (enddate is None):
        str_daycondition =  '''
                            KeyDate >= '%s' 
                            ''' %(begdate)
    elif (begdate is not None) & (enddate is not None):
        str_daycondition =  '''
                            (KeyDate >= '%s') and (KeyDate <= '%s')
                            ''' %(begdate,enddate)
    elif (begdate is None) & (enddate is None):
        str_daycondition =  None
    
    # 提取数据的查询语句
    if (indicators is None) & (str_daycondition is None):
        str_existedinfo = '''
                        select * from FI_CBSeriesIndicators
                        ''' 
    elif (indicators is None) & (str_daycondition is not None):
        str_existedinfo = '''
                        select * from FI_CBSeriesIndicators
                        where %s
                        ''' %(str_daycondition)
    elif (indicators is not None) & (str_daycondition is None):
        str_indicator = "','".join(indicators)
        str_existedinfo = '''
                        select * from FI_CBSeriesIndicators
                        where Indicator in ('%s')
                        ''' %(str_indicator)
    elif (indicators is not None) & (str_daycondition is not None):
        str_indicator = "','".join(indicators)
        str_existedinfo = '''
                        select * from FI_CBSeriesIndicators
                        where Indicator in ('%s')
                        and %s
                        ''' %(str_indicator,str_daycondition)
    
    cursor.execute(str_existedinfo)
    existed_info = pd.DataFrame(cursor.fetchall(),
                                columns=['Indicator','SecuCode','KeyDate','Value'])
    
    # 修正DataFrame的数据保存方式
    existed_info = pd.pivot(existed_info, values='Value', index=['SecuCode','KeyDate'], columns='Indicator')
    existed_info = existed_info.reset_index()\
        .rename(columns={'KeyDate':'date','SecuCode':'InnerCode'})\
        .astype({'date':'<M8[ns]','InnerCode':int})
        
    return existed_info


# %%

# 百元转债溢价率
def get_his_adjpremiumRate(enddate):
    enddatestr = enddate.strftime('%Y-%m-%d')
    variable_prefix = 'FICC|CBFitPremiumRateWithConvertValue'
    
    '''infodb的数据'''
    # 打开服务器
    conn_zs = pymssql.connect(host=server_zs, database="DataCenter", charset='cp936')
    cursor_zs = conn_zs.cursor()
    # 历史上的模型拟合结果
    existedinfo = get_existedinfo(cursor_zs, variable_prefix+'_par', enddate = enddatestr,
                                  useenddate = True)   
    # 关闭服务器
    cursor_zs.close()
    conn_zs.close()
    
    '''# 数据准备'''
    his_model_all = existedinfo.drop(columns='SecuCode').pivot_table(values='Value',columns='Indicator',index = 'KeyDate')
    
    his_model_all.columns = list(tmpc[len(variable_prefix)+1:] for tmpc in his_model_all.columns)
    
    his_model_all.columns = list(tmpc[4:] for tmpc in his_model_all.columns)
    # hs300 = pd.merge(hs300,PE,on='date')
    
    his_model_all.columns = his_model_all.columns.astype(int)
    
    return his_model_all

# %% 赎回进度数据






































































